import Vue from 'vue';
const drag = Vue.directive('drag', {
  // 当被绑定的元素插入到 DOM 中时……
  inserted: function (el, data) {
    // 聚焦元素
    // console.log(el, data);
    el.onmousedown = function (e) {
      if (e.target.id === data.value || !data.value) {
        el.style.position = 'absolute'
        var disx = e.pageX - el.offsetLeft;
        var disy = e.pageY - el.offsetTop;
        document.onmousemove = function (e) {
          let positionLeft = e.pageX - disx;
          let positionTop = e.pageY - disy;
          let winWidth = window.innerWidth;
          let winHeight = window.innerHeight;;
          if (positionLeft <= 0) positionLeft = 0;
          if (positionTop <= 0) positionTop = 0;
          if (positionLeft > winWidth - el.offsetWidth) positionLeft = winWidth - el.offsetWidth;
          if (positionTop > winHeight - el.offsetHeight) positionTop = winHeight - el.offsetHeight;
          el.style.left = positionLeft + 'px';
          el.style.top = positionTop + 'px';
        }
        document.onmouseup = function () {
          document.onmousemove = document.onmouseup = null;
        }
      }
    }
  }
})
export default drag;